import React, { useState, useEffect, useRef, useCallback } from 'react';
import { Input, Spin } from 'antd';
import { SearchOutlined } from '@ant-design/icons';
import dayjs from 'dayjs';
import utc from 'dayjs/plugin/utc';
import timezone from 'dayjs/plugin/timezone';
dayjs.extend(utc);
dayjs.extend(timezone);
import chatService from '@/api/services/chatService';
import { useParams } from '@/router/hooks';
import useWindowWidth from '@/hooks/event/use-window-width';

import { removeRefTags } from '@/utils/regexRules';
import { debounce } from 'lodash';

import './styles/history.css';
import NotData from '@/components/NotData';
import { historicalDialogueType } from '@/common';
import { SvgIcon } from '@/components/icon';
import { useOrchestrationStore } from '@/store/orchestrationStore';

interface HistoryChatProps {
  onChatItemClick?: (chatId: string) => void;
  onChangeChatItem?: (data: historicalDialogueType) => void;
  isSearch?: string | null;
  isCancel?: boolean | null;
  isDeleteChatHistory?: boolean;
  dataId?: string[];
}

const App: React.FC<HistoryChatProps> = ({
  onChatItemClick,
  onChangeChatItem,
  isSearch = '',
  isCancel,
  isDeleteChatHistory,
  dataId = [],
}) => {
  const pageSizeDefault = 50;
  const [chatHistory, setChatHistory] = useState<any[]>([]);
  const [pageNum, setPageNum] = useState(1);
  const [pageSize, setPageSize] = useState(pageSizeDefault);
  const [searchQuery, setSearchQuery] = useState('');
  const [loading, setLoading] = useState(false);
  const [hasMore, setHasMore] = useState(true);
  const containerRef = useRef<HTMLDivElement>(null);
  const historyListRef = useRef<HTMLDivElement>(null);

  const { appId } = useParams() as { appId: string };

  const [isInChatPage, setIsInChatPage] = useState<boolean>(false);

  const { appDetail } = useOrchestrationStore();
  useEffect(() => {
    const isChatPath = location.pathname.includes('/apps/chat');
    setIsInChatPage(isChatPath);
  }, [location.pathname, setIsInChatPage]);

  useEffect(() => {
    appId && debouncedGetHistoryData();
  }, [appId, pageNum, searchQuery, pageSize, isDeleteChatHistory]);

  useEffect(() => {
    if (isSearch != null) {
      setSearchQuery(isSearch);
    }
  }, [isSearch]);
  useEffect(() => {
    if (isCancel != null) {
      setSearchQuery('');
    }
  }, [isCancel]);

  const abortControllerRef = useRef<AbortController | null>(null);

  const getHistoryData = async () => {
    setLoading(true);
    try {
      if (appId) {
        const abortController = new AbortController();
        const { signal } = abortController;
        // 如果之前有未完成的请求，取消
        if (abortControllerRef.current) {
          abortControllerRef.current.abort();
        }
        abortControllerRef.current = abortController;

        const today = new Date();
        today.setHours(23, 59, 59, 999);
        const start = new Date();
        start.setHours(0, 0, 0, 0);
        start.setDate(today.getDate() - 7);
        const historyData = await chatService.getHistories(
          {
            appId: appId,
            pageNum: pageNum,
            pageSize: pageSize,
            dateStart: start.toISOString(),
            dateEnd: today.toISOString(),
            q: searchQuery,
            // isFusionApp: appDetail.appType === 'fusion' ? true : false,
            fusionAppId: appId,
            isGlobal: false, //所有应用true，反之false
          },
          signal,
        );

        const updatedData = historyData?.data || [];

        if (updatedData.length < pageSize) {
          setHasMore(false);
        }

        const groupedByDate = updatedData.reduce((acc: any, item: any) => {
          const beijingTime = dayjs.utc(item.time).tz('Asia/Shanghai');
          const date = beijingTime.format('YYYY-MM-DD');
          const today = dayjs().tz('Asia/Shanghai').format('YYYY-MM-DD');

          const displayDate = date === today ? '今天' : date;

          if (!acc[date]) {
            acc[date] = { time: displayDate, child: [] };
          }
          acc[date].child.push(item);
          return acc;
        }, {} as { [key: string]: { time: string; child: any[] } });

        const result = Object.keys(groupedByDate).map((key) => groupedByDate[key]);

        if (pageNum === 1) {
          setChatHistory(result);
        } else {
          const mergedHistory = [...chatHistory, ...result].reduce((acc, item) => {
            const existingItem = acc.find((i: any) => i.time === item.time);
            if (existingItem) {
              existingItem.child.push(...item.child);
            } else {
              acc.push(item);
            }
            return acc;
          }, []);

          // 按日期排序
          mergedHistory.sort((a: any, b: any) => {
            const dateA = a.time === '今天' ? dayjs().format('YYYY-MM-DD') : a.time;
            const dateB = b.time === '今天' ? dayjs().format('YYYY-MM-DD') : b.time;
            return dayjs(dateB).diff(dayjs(dateA));
          });

          setChatHistory(mergedHistory);
        }
      }
    } catch (error) {
      console.error(error);
    } finally {
      setLoading(false);
    }
  };

  const debouncedGetHistoryData = debounce(getHistoryData, 300);

  const onInputChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    setSearchQuery(e.target.value);
    setPageNum(1);
    setPageSize(pageSizeDefault);
    setHasMore(true);
  };

  const handleScroll = useCallback(() => {
    if (historyListRef.current) {
      const { scrollTop, scrollHeight, clientHeight } = historyListRef.current;

      if (scrollHeight - scrollTop <= clientHeight + 100 && !loading && hasMore) {
        setLoading(true);
        setPageSize((prevPageSize) => prevPageSize + pageSizeDefault);
      }
    }
  }, [loading, hasMore]);

  useEffect(() => {
    const container = historyListRef.current;
    if (container) {
      container.addEventListener('scroll', handleScroll);
    }
    return () => {
      if (container) {
        container.removeEventListener('scroll', handleScroll);
      }
    };
  }, [handleScroll]);

  const { isPc } = useWindowWidth();

  const handleChatItemClick = (item: historicalDialogueType) => {
    if (onChangeChatItem) {
      onChangeChatItem(item);
    }
    if (onChatItemClick) {
      onChatItemClick(item._id);
    }
  };

  return (
    <div
      className="w-full"
      style={{
        // backgroundColor: '#EDF0F8',
      }}
    >
      <div
        className={`h-full w-full ${!isPc && 'overflow-auto [-ms-overflow-style:none] [scrollbar-width:none]'
          }`}
        ref={containerRef}
        style={{
          // height: isPc ? 'calc(100vh - 200px)' : 'calc(100vh - 110px)',
          height: isPc ? 'unset' : 'calc(100vh - 90px)',
        }}
      >
        <div
          className={`mx-auto max-w-4xl ${isPc ? '' : 'px-2'}`}
          style={{
            width: isPc ? '800px' : '100%',
          }}
        >
          <div>
            <div
              style={{
                paddingTop: '20px',
              }}
            >
              <Input
                placeholder="搜索最近7天历史会话..."
                allowClear
                prefix={<SearchOutlined className="text-gray-400" />}
                className="rounded-lg border-gray-200 py-2"
                style={{
                  borderRadius: '12px',
                  height: '55px',
                  border: '1px solid #E5E5E5',
                }}
                onChange={onInputChange}
              />
            </div>
          </div>

          <div
            className="scrollbar-hide space-y-8"
            ref={historyListRef}
            style={{
              // maxHeight: isPc ? 'calc(100vh - 280px)' : 'calc(100vh - 200px)',
              maxHeight: isPc
                ? isInChatPage
                  ? 'calc(100vh - 180px)'
                  : 'calc(100vh - 280px)'
                : 'calc(100vh - 200px)',
              overflowY: 'auto',
              marginTop: '20px',
              scrollbarWidth: 'none' /* Firefox */,
              msOverflowStyle: 'none' /* IE and Edge */,
            }}
          >
            {chatHistory.map((day, dateIndex) => (
              <div key={dateIndex}>
                <div
                  className="mb-4 mt-4 text-sm"
                  style={{
                    fontSize: '24px',
                    fontWeight: '700',
                  }}
                >
                  {day.time}
                </div>
                <div>
                  {day.child.map((msg: any, msgIndex: number) => {
                    return (
                      <div
                        onClick={() => handleChatItemClick(msg)}
                        key={msgIndex}
                        style={{
                          flexDirection: 'column',
                          alignItems: 'flex-start',
                          marginBottom: '8px',
                        }}
                        className="group relative flex cursor-pointer rounded-lg bg-white p-2 transition-shadow hover:shadow-sm"
                      >
                        <div
                          className={`cursor-pointer justify-between hover:text-purple`}
                          style={{
                            width: '100%',
                            height: msg?.highlight_content ? 'unset' : '30px',
                            lineHeight: msg?.highlight_content ? 'unset' : '30px',
                            flex: 1,
                            overflow: 'hidden',
                            whiteSpace: 'nowrap',
                            textOverflow: 'ellipsis',
                            fontWeight: msg?.highlight_content ? '700' : 'unset',
                            display: 'flex',
                          }}
                        >
                          <div
                            style={{ marginRight: '5px' }}
                            className="flex items-center justify-center"
                          >
                            {' '}
                            📑
                            <div
                              id="highlight"
                              className="pl-2 text-gray-700"
                              style={{
                                width: isPc ? 'unset' : '200px',
                                flex: 1,
                                overflow: 'hidden',
                                whiteSpace: 'nowrap',
                                textOverflow: 'ellipsis',
                              }}
                              dangerouslySetInnerHTML={{ __html: removeRefTags(msg?.title) }}
                            ></div>
                          </div>
                          <div className="group flex items-center">
                            <div
                              className="time flex-shrink-0 text-sm text-gray-400"
                              style={{ width: isPc ? '160px' : '60px' }}
                            >
                              {dayjs(msg.time).format(isPc ? 'YYYY-MM-DD HH:mm:ss' : 'HH:mm:ss')}
                            </div>
                          </div>
                        </div>

                        {msg?.highlight_content && (
                          <div
                            id="highlight"
                            style={{
                              width: '100%',
                              flex: 1,
                              overflow: 'hidden',
                              whiteSpace: 'nowrap',
                              textOverflow: 'ellipsis',
                              fontSize: '12px',
                              marginTop: '5px',
                            }}
                            dangerouslySetInnerHTML={{
                              __html: removeRefTags(msg?.highlight_content),
                            }}
                          ></div>
                        )}
                      </div>
                    );
                  })}
                </div>
              </div>
            ))}
            {loading && (
              <div className="py-4 text-center">
                <Spin />
              </div>
            )}
            {!hasMore && chatHistory?.length == 0 && <NotData />}
            {!hasMore && chatHistory?.length > 0 && (
              <div className="py-4 text-center">没有更多数据了</div>
            )}
          </div>
        </div>
      </div>
    </div>
  );
};

export default App;
